package com.zc.easy.No21;

/**
 * @program: leetCode_Exercise
 * @author: zhangcong
 * @create: 2019-09-19 17:55
 * @description: 合并连个有序链表
 * 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
 * <p>
 * 示例：
 * <p>
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 **/
public class Solution {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

    }


    //l1小于l2,
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

    private static void test(ListNode listNode, int i) {
        listNode.next = new ListNode(i);
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 4};
        ListNode listNode1 = new ListNode(a[0]);
        ListNode temp = listNode1;
        for (int i = 1; i < a.length; i++) {
            test(temp, a[i]);
            temp = temp.next;
        }

        int[] b = {1, 3, 4};
        ListNode listNode2 = new ListNode(b[0]);
        ListNode temp2 = listNode2;
        for (int i = 1; i < b.length; i++) {
            test(temp2, b[i]);
            temp2 = temp2.next;
        }
        ListNode twoNumbers = mergeTwoLists(listNode1, listNode2);
        while (twoNumbers != null) {
            System.out.print(twoNumbers.val + "--->");
            twoNumbers = twoNumbers.next;
        }
    }
}
